package com.zimmur.service.impl.order;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.zimmur.common.AppModuleEnum;
import com.zimmur.common.IDWorkFactory;
import com.zimmur.dao.order.IOrderDetailDao;
import com.zimmur.dao.order.IOrderServiceDao;
import com.zimmur.dao.order.IOrderServiceDetailDao;
import com.zimmur.dao.order.IOrderServiceImageDao;
import com.zimmur.model.fdfs.StorageFiles;
import com.zimmur.model.goods.GoodsColor;
import com.zimmur.model.goods.OrderServiceParam;
import com.zimmur.model.goods.WishListResParam;
import com.zimmur.model.order.Order;
import com.zimmur.model.order.OrderDetail;
import com.zimmur.model.order.OrderService;
import com.zimmur.model.order.OrderServiceDetail;
import com.zimmur.model.order.OrderServiceImage;
import com.zimmur.model.order.view.CustomerServiceView;
import com.zimmur.model.order.view.OrderParameter;
import com.zimmur.model.order.view.OrderServiceView;
import com.zimmur.service.fdfs.IStorageFilesService;
import com.zimmur.service.goods.IGoodsOrganizationService;
import com.zimmur.service.order.IOrderDetailService;
import com.zimmur.service.order.IOrderService;
import com.zimmur.service.order.IOrderServiceService;
import com.zimmur.tools.DateUtils;
import com.zimmur.tools.PageUtil;
@Service("orderServiceServiceImpl")
public class OrderServiceServiceImpl implements IOrderServiceService{
	@Resource
	private IOrderServiceDao orderServiceDao;
	@Resource
	private IOrderServiceDetailDao orderServiceDetailDao;
	@Resource
	private IOrderServiceImageDao orderServiceImageDao;
	@Resource
	private IOrderDetailDao orderDetailDao;
	@Resource
	private IOrderService orderService;
	@Resource
	private IOrderDetailService orderDetailService;
	@Resource
	private IGoodsOrganizationService goodsOrganizationService;
	@Resource
	private IStorageFilesService storageFilesService;
	
	@Override
	public int insertSelective(OrderService record) {
		return orderServiceDao.insertSelective(record);
	}

	@Override
	public int updateByPrimaryKeySelective(OrderService record) {
		return orderServiceDao.updateByPrimaryKeySelective(record);
	}

	@Override
	public int updateByOrderId(OrderService record) {
		return orderServiceDao.updateByOrderId(record);
	}

	@Override
	public PageUtil<Order> selectByUserIdList(long userId,Integer pageNow,String serviceStatus,int time,String keyword) {
		PageUtil<Order> page = new PageUtil<>();
		List<Order> orderList = new ArrayList<>();
		try {
			if(pageNow == 0){
				pageNow=1;
			}
			Integer totalRecord = orderServiceDao.selectByUserIdCount(userId);
			page.setPageNo(pageNow);
			page.setTotalRecord(totalRecord);
					
			List<OrderService> orderServiceList = orderServiceDao.selectByUserIdList(page.getPageBeginNo(),page.getPageSize(),userId,serviceStatus,time,keyword);
			for(OrderService orderServiceItem : orderServiceList){
				Order order = orderService.selectByOrderId(Long.parseLong(orderServiceItem.getOrderId()));
				OrderServiceView orderServiceView=order.getServiceView();
				orderServiceView.setServiceId(Long.parseLong(orderServiceItem.getServiceId()));
				orderServiceView.setShipCompany(orderServiceItem.getShipCompany());
				orderServiceView.setShipNo(orderServiceItem.getShipNo());
				orderServiceView.setIsFinish(orderServiceItem.getIsFinish());
				if(orderServiceItem.getShopShipDate()!=null){
					orderServiceView.setShipDate(DateUtils.getFormatDateFromUnixTime(orderServiceItem.getShipDate(),"YYYY-MM-dd"));
					
				}
				List<OrderDetail> orderDetaiLsit = orderDetailService.selectByPrimaryKey(Long.parseLong(orderServiceItem.getServiceId()));
				order.setOrderDetailList(orderDetaiLsit);
				orderList.add(order);
			}
			if(!orderList.isEmpty() && orderList.size() > 0 ){
				page.setItemList(orderList);
			}
		} catch (Exception e) {
			e.getMessage();
		}
		return page;
	}
	@Transactional(propagation=Propagation.REQUIRES_NEW,rollbackFor={Exception.class})
	@Override
	public Long createOrderService(Long userId, String content, String imageS, Long orderId, String orderDetailIdS,
			Short isService) {
		Integer flag = 0;
		Integer timeDate =DateUtils.getUnixTimeByDate(DateUtils.getNow());//获取当前时间，转为INT存储	
		OrderService orderServiceModel = new OrderService();
		String[] sArr=orderDetailIdS.split(",");
		Long serviceId = 0L;
		//1.生成售后单，售后单明细，售后单凭据
		if(isService!=10){//申请退货与申请换货
			if(sArr[0] != "" && sArr.length > 0){
				//1.1.填充售后单数据
				orderServiceModel.setContent(content);
				orderServiceModel.setUserId(userId+"");//添加申请人
				orderServiceModel.setOrderId(orderId+"");
				orderServiceModel.setIsService(isService);
				orderServiceModel.setCreateDate(timeDate);
				orderServiceModel.setApplyText("售后中,待审核");
				orderServiceModel.setAppyDate(timeDate);
				//
				serviceId = IDWorkFactory.getID(AppModuleEnum.Order);
				//1.2.添加售后单明细并修改订单明细
				for(String s:sArr){
					long orderDetailIdNew=Long.parseLong(s);
					OrderDetail orderDetail = orderDetailDao.selectByPrimaryKey(orderDetailIdNew);
					if(orderDetail!=null){
						//修改订单明细的售后状态
						orderDetail.setIsService(isService);
						orderDetailDao.updateOrderDetailServiceStatus(orderDetail);
						//添加售后订单明细
						Long recId =IDWorkFactory.getID(AppModuleEnum.UserCenter);
						OrderServiceDetail orderServiceDetail = new OrderServiceDetail();
						orderServiceDetail.setCreateDate(timeDate);
						orderServiceDetail.setOrderDetailId(Long.parseLong(s));
						orderServiceDetail.setQuantity(orderDetail.getQuantity());
						orderServiceDetail.setRecId(recId);
						orderServiceDetail.setServiceId(serviceId);
						orderServiceDetail.setUserId(userId);
						orderServiceDetail.setOrderId(orderId);
						orderServiceDetailDao.insertSelective(orderServiceDetail);
					}
				}
				//添加售后单
				orderServiceModel.setServiceId(serviceId+"");
				flag = orderServiceDao.insertSelective(orderServiceModel);
				//1.3.添加售后凭据信息
				if(flag > 0){
					String[] sArrimageS=imageS.split(",");
					if(!sArrimageS[0].equals("") && sArrimageS.length > 0){
						OrderServiceImage orderServiceImage = new OrderServiceImage();
						for(String image:sArrimageS){		    	
							Long recId =IDWorkFactory.getID(AppModuleEnum.UserCenter);
							orderServiceImage.setServiceId(serviceId);
							orderServiceImage.setImage(image);
							orderServiceImage.setRecId(recId);
							orderServiceImageDao.insertOrderServiceImage(orderServiceImage);
						}
					}
				}
			}
		}else{//整单申请退款
			//1.1.填充售后单数据
			orderServiceModel.setContent(content);
			orderServiceModel.setUserId(userId+"");//添加申请人
			orderServiceModel.setOrderId(orderId+"");
			orderServiceModel.setIsService(isService);
			orderServiceModel.setCreateDate(timeDate);
			orderServiceModel.setApplyText("售后中,待审核");
			
			orderServiceModel.setAppyDate(timeDate);
			//1.2.添加售后单明细并修改订单明细
			double backAmountJe = 0d;//退还金额
			serviceId =IDWorkFactory.getID(AppModuleEnum.Order);
			List<OrderDetail> orderDetailList = orderDetailDao.selectByOrderId(orderId);
			if(orderDetailList!=null&&orderDetailList.size()>0){
				for(OrderDetail orderDetail:orderDetailList){
					//修改订单明细的售后状态
					orderDetail.setIsService(isService);
					backAmountJe += orderDetail.getShareAmount();//申请退款记录售后单记录订单明细中退款金额
					orderDetailDao.updateOrderDetailServiceStatus(orderDetail);
					//添加售后订单明细
					Long recId =IDWorkFactory.getID(AppModuleEnum.UserCenter);
					OrderServiceDetail orderServiceDetail = new OrderServiceDetail();
					orderServiceDetail.setCreateDate(timeDate);
					orderServiceDetail.setOrderDetailId(Long.parseLong(orderDetail.getOrderDetailId()));
					orderServiceDetail.setQuantity(orderDetail.getQuantity());
					orderServiceDetail.setRecId(recId);
					orderServiceDetail.setServiceId(serviceId);
					orderServiceDetail.setUserId(userId);
					orderServiceDetail.setOrderId(orderId);
					orderServiceDetailDao.insertSelective(orderServiceDetail);
				}
			}
			//1.3.添加售后单
			orderServiceModel.setServiceId(serviceId+"");
			orderServiceModel.setServiceJe(backAmountJe);
			flag =  orderServiceDao.insertSelective(orderServiceModel);
			if(flag>0){
				Order order = orderService.selectByOrderId(orderId);
				order.setOderStatus("40");
				order.setOrderStatusText("待退款");
				orderService.updateByPrimaryKeySelective(order);
			}
		}
		//返回售后单号
		return serviceId;
	}

	@Override
	public OrderService queryByServerIdAndOrderId(Long serviceId, Long orderId) {
		return orderServiceDao.selectByServerIdAndOrderId(serviceId,orderId);
	}
	@Override
	public PageUtil<CustomerServiceView> queryServiceList(OrderServiceParam param) {
		PageUtil<CustomerServiceView> page = new PageUtil<CustomerServiceView>();
		int count = orderServiceDao.countByParam(param);
		List<CustomerServiceView> list = orderServiceDao.readByMuchParams(param);

		if (list != null && !list.isEmpty()) {
			for (CustomerServiceView v : list) {
				// 查询售后单明细
				List<OrderServiceDetail> detailList = orderServiceDetailDao
						.selectByServiceId(Long.parseLong(v.getServiceId()));
				// 查询订单明细
				List<OrderDetail> orderDetailList = new ArrayList<>();
				if (detailList != null & detailList.size() > 0) {
					for (OrderServiceDetail item : detailList) {
						OrderDetail orderDetail = orderDetailDao.selectByKey(item.getOrderDetailId());
						orderDetailList.add(orderDetail);
					}
				}
				v.setOrderDetailList(orderDetailList);
			}
		}
		page.setTotalRecord(count);
		page.setPageNo(param.getPageIndex());
		page.setPageSize(param.getPageSize());
		page.setItemList(list);
		return page;
	}

	@Override
	public OrderService queryCustServiceDetail(Long serviceId) {
		// 1.查询订单服务
		OrderService orderService = orderServiceDao.selectCustServiceDetail(serviceId);
		if (orderService != null && orderService.getImageList() != null && !orderService.getImageList().isEmpty()) {
			for (OrderServiceImage image : orderService.getImageList()) {
				// 2.查询售后凭据信息
				if(!StringUtils.isEmpty(image.getImage())){
					StorageFiles storageFiles = storageFilesService.selectByFileId(Long.parseLong(image.getImage()));
					if (storageFiles != null) {
						image.setImageUrl("/" + storageFiles.getStoragegroup() + "/" + storageFiles.getStorageid());
					}
				}
			}
		}
		if(orderService != null){
			// 3.查询售后单明细
			List<OrderServiceDetail> detailList = orderServiceDetailDao.selectByServiceId(serviceId);
			// 4.查询订单明细
			List<OrderDetail> orderDetailList = new ArrayList<>();
			if (detailList != null & detailList.size() > 0) {
				for (OrderServiceDetail item : detailList) {
					OrderDetail orderDetail = orderDetailDao.selectByKey(item.getOrderDetailId());
					orderDetailList.add(orderDetail);
				}
				orderService.setOrderDetailList(orderDetailList);
			}
		}
		return orderService;
	}

	@Override
	public OrderService queryCustServiceById(Long serviceId) {
		return orderServiceDao.selectByPrimaryKey(serviceId);
	}
}
